package com.ssyc.student.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ssyc.common.base.LazyBaseFragment;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.MyListView;
import com.ssyc.student.R;
import com.ssyc.student.adapter.StErrorAnswerLvAdapter;
import com.ssyc.student.bean.ErrorQuestionsInfo;
import com.ssyc.student.bean.StAnswerInfo;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--语法错题集--单选题fragment
 * Created by Kevin on 2018/5/30
 */

public class StudentErrorSingleChooseFragment extends LazyBaseFragment {

    //阅读的题目内容
    private TextView tvTopic;

    //展示答案选项的ListView
    private MyListView lvAnswer;


    //展示正确的完整句子
    private TextView tvShowContent;

    //选择正确答案后需要展示的整体布局,默认不显示
    private LinearLayout llShowAnswer;


    //提供选择答案的数据集合
    private List<StAnswerInfo> answerInfos;

    //展示答案选项的列表适配器
    private StErrorAnswerLvAdapter adapter;

    //当前题目的位置
    private int currPos;


    //通知Acitvity进行ViewPager翻页的标识
    public static String VPSCOLL = "StudentGrammarDetectionActivityVpScoll";


    //当前题目的正确答案,通过传值获取
    public String correctAnswer = "rightAnswer";

    //题目内容
    private List<ErrorQuestionsInfo.DataBean.ErrorListBean> datas;

    //A到Z的数据集合
    private String[] chartNums;


//    private TextView tv_answer_num;

    //你的作答
    private TextView tv_explain;

    //班级正确率
    private TextView tv_class_accuracy;

    //全校正确率
    private TextView tv_school_accuracy;

    //错误选项
    private TextView tv_false_flag;
    //正确选项
    private TextView tv_true_flag;

    //移除
    private ImageView iv_del;

    //超越目标
    private TextView tv_overshoot;

    //未答对学生
    private TextView tv_notright_stu;


    //移除题目后刷新数据
    public static final String DELREFLASH = "delreflash";

    /**
     * 提供的生成当前Fragment的方法
     *
     * @param data 包含页面数据的json字符串
     * @return
     */
    public static StudentErrorSingleChooseFragment newInstance(String data, int pos) {

        StudentErrorSingleChooseFragment studentErrorSingleChooseFragment = new StudentErrorSingleChooseFragment();
        Bundle bundle = new Bundle();
        bundle.putString("data", data);
        bundle.putInt("pos", pos);
        studentErrorSingleChooseFragment.setArguments(bundle);

        return studentErrorSingleChooseFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_student_error_single_choose;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    public void lazyInit(View view, Bundle savedInstanceState) {
        //初始化视图
        initView(view);

        showContent();

        //模拟提供答案选项的数据
        initData();

        //设置展示答案的ListView
        initLv();
    }


    /**
     * 初始化视图
     *
     * @param view
     */
    public void initView(View view) {
        tvTopic = view.findViewById(R.id.tv_topic);
        lvAnswer = view.findViewById(R.id.lv_answer);
        tvShowContent = view.findViewById(R.id.tv_show_content);
        llShowAnswer = view.findViewById(R.id.ll_show_answer);

        tv_false_flag = view.findViewById(R.id.tv_false_flag);
        tv_true_flag = view.findViewById(R.id.tv_true_flag);

        tv_explain = view.findViewById(R.id.tv_explain);
        tv_class_accuracy = view.findViewById(R.id.tv_class_accuracy);
        tv_school_accuracy = view.findViewById(R.id.tv_school_accuracy);

        tv_overshoot = view.findViewById(R.id.tv_overshoot);

        tv_notright_stu = view.findViewById(R.id.tv_notright_stu);

        iv_del = view.findViewById(R.id.iv_del);
        iv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //弹框
                PopUpManager.showPop(getActivity(), R.layout.st_pop_error_quetions,
                        0.3f, getActivity(), new PopUpManager.onGetViewListener() {
                            @Override
                            public void getChildView(View view, int layoutResId) {
                                //关闭按钮
                                ImageView ivClose = view.findViewById(R.id.lv_close);
                                Button btCommit = view.findViewById(R.id.bt_commit);
                                ivClose.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        //关闭弹框
                                        PopUpManager.dismiss();
                                    }
                                });
                                btCommit.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        //移除题目
                                        delErrorQuestions();
                                        //关闭弹框
                                        PopUpManager.dismiss();
                                    }
                                });
                            }
                        });
            }
        });
    }


    /**
     * 移除错题
     */
    private void delErrorQuestions() {

        Map<String, String> map = new HashMap<>();
        map.put("type", "33");
        map.put("acc", AccountUtils.getAccount(getActivity()));
        map.put("role", "0");
        map.put("lessonId", datas.get(currPos).getLessonId().replace("Lesson", ""));
        map.put("moduleId", datas.get(currPos).getModuleId());
        map.put("typeId", datas.get(currPos).getTypeId());
        map.put("questionId", datas.get(currPos).getQuestionId());
        map.put("apptoken", AccountUtils.getToken(getActivity()));
        map.put("platform", "8");
//        map.put("acc", "15608630008");
//        map.put("lessonId", "1");
//        map.put("apptoken", "WHBHWJDSAKDAKSDNSAJDAK");

        HttpUtils.post(HttpAdress.ERRORQUESTIONS, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                UiUtils.Toast("网络错误", false);
            }

            @Override
            public void onResponse(String response, int id) {
                showContent();
                ErrorQuestionsInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, ErrorQuestionsInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "数据解析异常");
                }
//                Log.i("test", "错题集："+response);
                if (null != info) {
                    if ("200".equals(info.getState())) {
                        //返回成功
                        UiUtils.Toast("移除成功", false);
                        //EventBus通知Activity进行移除界面
                        EventBus.getDefault().post(new BusInfo(DELREFLASH, currPos));
                    } else {
                        Log.i("test", info.getState());
                        UiUtils.Toast("移除失败", false);
                    }
                }
            }
        });
    }

    /**
     * 答案选项
     */
    private void initData() {


        chartNums = getContext().getResources().getStringArray(R.array.base_letters);
        //获取当前页面的位置
        currPos = getArguments().getInt("pos");

        //获取传递过来的页面数据
        String dataJson = getArguments().getString("data");
        //解析该Json获取页面数据
        answerInfos = new ArrayList<>();
        datas = new ArrayList<>();
        datas = GsonUtil.jsonToBean(dataJson, ErrorQuestionsInfo.DataBean.class).getError_list();


        //答案
        correctAnswer = datas.get(currPos).getAnswer();


        //保证存放的每个位置都对应有值
//        StudentGrammarDetectionActivity.getChooseAnswerMap().put(lastPos+currPos, "");

        //设置选项列表
        answerInfos = new ArrayList<>();
        for (int i = 0; i < datas.get(currPos).getOptions().size(); i++) {
            if (datas.get(currPos).getExplain().equals(datas.get(currPos).getOptions().get(i))) {
                answerInfos.add(new StAnswerInfo(true, datas.get(currPos).getOptions().get(i)
                        , chartNums[i]));
            } else {
                answerInfos.add(new StAnswerInfo(false, datas.get(currPos).getOptions().get(i)
                        , chartNums[i]));
            }
        }
        //设置我的作答选项
        for (int i = 0; datas.get(currPos).getOptions().size() > i; i++) {
            if (datas.get(currPos).getExplain().equals(datas.get(currPos).getOptions().get(i))) {
                tv_false_flag.setText(chartNums[i]);
            }
        }

        //设置正确答案选项
        for (int i = 0; datas.get(currPos).getOptions().size() > i; i++) {
            if (datas.get(currPos).getAnswer().equals(datas.get(currPos).getOptions().get(i))) {
                tv_true_flag.setText(chartNums[i]);
            }
        }


        //设置题目
        tvTopic.setText(datas.get(currPos).getSmall_title().replaceAll("填空", "___"));
        //设置你的作答
        tv_explain.setText(datas.get(currPos).getExplain());

        //设置正确答案
        tvShowContent.setText(datas.get(currPos).getAnswer());

        //设置班级正确率
        tv_class_accuracy.setText("班级正确率：" + datas.get(currPos).getClass_correct() + "%");

        //设置全校正确率
        tv_school_accuracy.setText("全校正确率：" + datas.get(currPos).getSchool_correct() + "%");

//        if(datas.get(currPos).getAnswer().equals(datas.get(currPos).getOptions().get(0))){
//            tv_answer_num.setText("A");
//        }else if(datas.get(currPos).getAnswer().equals(datas.get(currPos).getOptions().get(1))){
//            tv_answer_num.setText("B");
//        }else if(datas.get(currPos).getAnswer().equals(datas.get(currPos).getOptions().get(2))){
//            tv_answer_num.setText("C");
//        }else {
//            tv_answer_num.setText("D");
//        }

        //是否是教师端
        if ("2".equals(AccountUtils.getRole(getActivity()))) {
            tv_overshoot.setVisibility(View.VISIBLE);
            tv_notright_stu.setVisibility(View.VISIBLE);
            iv_del.setVisibility(View.GONE);
            tv_false_flag.setVisibility(View.GONE);

            //设置超越目标
            if (datas.get(currPos).getTranscend().size() != 0) {
                String temp = "";
                for (int i = 0; i < datas.get(currPos).getTranscend().size(); i++) {
                    temp = datas.get(currPos).getTranscend().get(i) + " ";
                }
                tv_overshoot.setText("超越目标：" + temp);
            } else {
                tv_overshoot.setText("超越目标：暂无");
            }

            //设置未答对人
            if (datas.get(currPos).getStu_error().size() != 0) {
                String tem = "";
                for (int i = 0; i < datas.get(currPos).getStu_error().size(); i++) {
                    tem = datas.get(currPos).getStu_error().get(i) + " ";
                }
                tv_notright_stu.setText("未答对人：" + tem);
            } else {
                tv_notright_stu.setText("未答对人：暂无");
            }
        }
    }

    /**
     * 设置展示选择答案的ListView
     */
    private void initLv() {
        adapter = new StErrorAnswerLvAdapter(getContext(), answerInfos,
                R.layout.student_lv_answer, datas.get(currPos).getAnswer());
        lvAnswer.setAdapter(adapter);
    }
}
